//
//  NSString+UtilsExtras.m
//  SPay.base
//
//  Created by wongfish on 15/6/17.
//  Copyright (c) 2015年 wongfish. All rights reserved.
//

#import "NSString+UtilsExtras.h"
#import "NSData+UtilsExtras.h"
#import <CommonCrypto/CommonDigest.h>

@implementation NSString (UtilsExtras)
#pragma mark - md5加密
/**
 md5加密——32位
 @return md5字符串
 */
- (NSString*)md5Hash {
    return [[self dataUsingEncoding:NSUTF8StringEncoding] md5Hash];
}

/**
 md5加密——16位
 @return md5字符串
 */
-(NSString *)md5Hash16{
    NSString  *string;
    string=[self substringWithRange:NSMakeRange(8, 16)];
    return string;
}


#pragma mark - base64字符串
//base64字符串
- (NSString *)base64Encoding {
    NSData *stringData = [self dataUsingEncoding:NSUTF8StringEncoding];
    NSString *encodedString = [stringData base64EncodedString];
    return encodedString;
}


#pragma mark - SHA1
- (NSString*)sha1 {
    const char *cstr = [self cStringUsingEncoding:NSUTF8StringEncoding];
    NSData *data = [NSData dataWithBytes:cstr length:self.length];
    //使用对应的CC_SHA1,CC_SHA256,CC_SHA384,CC_SHA512的长度分别是20,32,48,64
    uint8_t digest[CC_SHA1_DIGEST_LENGTH];
    //使用对应的CC_SHA256,CC_SHA384,CC_SHA512
    CC_SHA1(data.bytes, (int)data.length, digest);
    
    NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
    for(int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++) {
        [output appendFormat:@"%02x", digest[i]];
    }
    return output;
}


#pragma mark - 是否为空
- (BOOL)isEmpty {
    return self.length == 0;
}

#pragma makr - 判断URL地址是否合法
- (BOOL)smartURLForString {
    if ((self == nil) || (self.length == 0)) {
        return NO;
    }
    return YES;
}


#pragma mark - URL编码解码
- (NSString *) stringByUrlEncoding {
   return (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(NULL,
                                                                          (CFStringRef)self,
                                                                          NULL,
                                                                          (CFStringRef)@"!*'();:@&=+$,/?%#[]",
                                                                          kCFStringEncodingUTF8));
//    NSCharacterSet *chatSet = [NSCharacterSet characterSetWithCharactersInString:@"!*'();:@&=+$,/?%#[]"];
//    return [self stringByAddingPercentEncodingWithAllowedCharacters:chatSet];
}

- (NSString *)stringByUrlDecoding {
    NSString *result = [(NSString *)self stringByReplacingOccurrencesOfString:@"+" withString:@" "];
    result = [result stringByRemovingPercentEncoding];
    return result;
}


#pragma mark - 字符串工具
//去除字符串前后的空白,包含换行符
- (NSString *)trim {
    return [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}

//去除字符串中所有空白
- (NSString *)removeWhiteSpace {
    return [[self componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]
            componentsJoinedByString:@""];
}

//第一个字符大写
- (NSString *)capitalize {
    if ([self length] == 0 || islower([self characterAtIndex:0]) == 0) return self;
    return [[self substringToIndex:1].uppercaseString stringByAppendingString:[self substringFromIndex:1]];
}

//第一个字符小写
- (NSString *)lowercaseFirstString {
    if ([self length] == 0 || isupper([self characterAtIndex:0]) == 0) return self;
    return [[self substringToIndex:1].lowercaseString stringByAppendingString:[self substringFromIndex:1]];
}


#pragma mark - 网址解析
//获取网址的绝对路径
- (NSString*)stringUrlAbsolutePath{
    NSRange range = [self rangeOfString:@"?"];
    if (range.location != NSNotFound) {
        NSString *urlAbsolutePath = [self substringToIndex:range.location];
        return urlAbsolutePath;
    }
    return self;
}

//解析HTTP中GET的请求参数
-(NSDictionary*)resolveHTTPGETParameter{
    NSRange range = [self rangeOfString:@"?"];
    NSString *hTTPGETParameterString = [self copy];
    
    //判断是否需要把网址移除
    if (range.location != NSNotFound) {
        hTTPGETParameterString = [self substringFromIndex:(range.location + range.length)];
    }
    
    NSArray *hTTPGETParameterArray = [hTTPGETParameterString componentsSeparatedByString:@"&"];
    //是否分割出来了参数
    if (hTTPGETParameterArray && hTTPGETParameterArray.count) {
        
        NSMutableDictionary *parameterDicy = [[NSMutableDictionary alloc] init];
        for (NSString *parameterItemString in hTTPGETParameterArray) {
            NSArray *itemArray = [parameterItemString componentsSeparatedByString:@"="];
            //判断参数格式是否合法
            if (itemArray && (itemArray.count == 2)) {
                [parameterDicy setValue:itemArray[1] forKey:itemArray[0]];
            }else{
                return nil;
            }
        }
        return parameterDicy;
    }
    return nil;
}


#pragma mark - json转换
//json字符串——字典
- (NSMutableDictionary*)parseResponseStringToJSON {
    id dic = nil;
    @try {
        NSError *error = nil;
        NSData *JSONData = [self dataUsingEncoding:NSUTF8StringEncoding];
        dic = [NSJSONSerialization JSONObjectWithData:JSONData
                                               options:NSJSONReadingMutableContainers
                                                 error:&error];
        if(error == nil && [NSJSONSerialization isValidJSONObject:dic]) {
            return dic;
        }
        return nil;
    }@catch (NSException *exception) {
        
    }@finally {
        
    }
}

//json字符串——数组
- (NSMutableArray*)parseResponseArrayStringToJSONArray{
    id array = nil;
    @try {
        NSError *error = nil;
        NSData *JSONData = [self dataUsingEncoding:NSUTF8StringEncoding];
        array = [NSJSONSerialization JSONObjectWithData:JSONData
                                               options:NSJSONReadingMutableContainers
                                                 error:&error];
        if(error == nil && [NSJSONSerialization isValidJSONObject:array]){
            return array;
        }
        return nil;
    } @catch (NSException *exception) {
        
    } @finally {
        
    }
}


#pragma mark - 密码位数限制
//spay登录密码是否6-20位
- (BOOL)isSPayLoginPassword{
    NSString *pwStr = [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    if (pwStr && ![pwStr isEmpty] && (pwStr.length) >= 6 && (pwStr.length <= 20)) {
        return YES;
    }
    return NO;
}

//新密码是否8-20位
- (BOOL)isSPayNewPassword {
    NSString *pwStr = [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    if (pwStr && ![pwStr isEmpty] && (pwStr.length >= 8) && (pwStr.length <= 20)) {
        return YES;
    }
    return NO;
}

#pragma mark - 单位转换（元——分）
//将钱单位转为分
- (long)stringToNSDecimalNumber {
    
    if ([self isEqualToString:@""]) {
        return 0;
    }
    
    NSString *moneyString = [self stringByReplacingOccurrencesOfString:@"," withString:@""];
    NSDecimalNumber *n = [NSDecimalNumber decimalNumberWithString:moneyString];
    NSDecimalNumber *y = [NSDecimalNumber decimalNumberWithString:@"100"];
    
    long l = [[n decimalNumberByMultiplyingBy:y] longValue];
    return l;
}


#pragma mark - 正则表达式校验
- (BOOL)isValidateByRegex:(NSString *)regex{
    NSPredicate *pre = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    return [pre evaluateWithObject:self];
}

#pragma mark - action —— 日期展示
//年－月－日
- (NSString*)subStringYearMonthDay {
    if (self.length >= 10) {
        NSRange range = NSMakeRange(0, 10);
        return [self substringWithRange:range];
    }
    return self;
}

//年－月
- (NSString*)subStringYearMonth {
    if (self.length >= 7) {
        NSRange range = NSMakeRange(0, 7);
        return [self substringWithRange:range];
    }
    return self;
}

//月－日
- (NSString*)subStringMothDay {
    if (self.length >= 10) {
        NSRange range = NSMakeRange(5, 5);
        return [self substringWithRange:range];
    }
    return self;
}

//月
- (NSString*)subStringMonth {
    if (self.length >= 7) {
        NSRange range = NSMakeRange(5, 2);
        NSString *month = [NSString stringWithFormat:@"%ld%@",(long)[self substringWithRange:range].integerValue,@"月"];
        return month;
    }
    return self;
}

//时:分:秒
- (NSString*)subStringTimeMinSecond {
    if (self.length >= 18) {
        NSRange range = NSMakeRange(self.length-8, 8);
        return [self substringWithRange:range];
    }
    return self;
}


#pragma mark - 金额单位，人民币为元
//返回金额单位，人民币为元
- (NSString *)getMoneyUnit {
    //打印时，币种为人民币，金额后面带元
    NSString *moneyUnit = @"";
    if ([self isEqualToString:@"CNY"]) {
        moneyUnit = @"元";
    } else {
        moneyUnit = @"";
    }
    return moneyUnit;
}

#pragma mark - 汉字的拼音
//汉字的拼音
- (NSString *)pinyin{
    NSMutableString *str = [self mutableCopy];
    CFStringTransform(( CFMutableStringRef)str, NULL, kCFStringTransformMandarinLatin, NO);
    CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformStripDiacritics, NO);
    
    return [str stringByReplacingOccurrencesOfString:@" " withString:@""].uppercaseString;
}

#pragma mark double转字符串
+ (NSString*)Rounding:(double)number afterPoint:(NSInteger)position
{
    if (number < 0.01 && number != 0) {
        return [NSString stringWithFormat:@"%.3f",number];
    }
  NSDecimalNumberHandler *handler = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode: NSRoundPlain scale: position raiseOnExactness: NO raiseOnOverflow: NO raiseOnUnderflow:NO raiseOnDivideByZero: NO];
  NSDecimalNumber *floatDecimal = [[NSDecimalNumber alloc] initWithFloat: number];
  NSDecimalNumber *resultNumber = [floatDecimal decimalNumberByRoundingAccordingToBehavior:handler];
  return [NSString stringWithFormat:@"%@",resultNumber];
}
@end
